<template>
    <!-- 模板部分保持不变 -->
    <view class="page">
        <view class="head">
            <!-- #ifdef APP-PLUS -->
            <view class="title">购物车</view>
            <!-- #endif -->
            <view class="edit" @click="isEdit = !isEdit">
                <text>{{isEdit?'完成':'编辑'}}</text>
            </view>
        </view>
        <!-- 购物车列表 -->
        <mescroll-body ref="mescrollRef"
                       @down="downCallback"
                       @up="upCallback"
                       :down="downOption"
                       :up="upOption"
                       :top="0">
            <view class="cart-list">
                <view class="list" v-for="(item, index) in list" :key="index">
                    <view class="check" @click="toggleItemSelection(index)">
                        <text class="iconfont" :class="{ 'icon-checked': item.selected, 'icon-uncheck':!item.selected }"></text>
                    </view>
                    <view class="goods">
                        <view class="thumb">
                            <image src="/static/img/goods_thumb_09.png" mode=""></image>
                        </view>
                        <view class="item">
                            <view class="title">
                                <text class="two-omit">{{item.description}}</text>
                            </view>
                            <view class="attribute">
                                <view class="attr">
                                    <text>{{item.pro_value_id1}},{{item.pro_value_id2}},{{item.pro_value_id3}}</text>
                                    <text class="more"></text>
                                </view>
                            </view>
                            <view class="price-num">
                                <view class="price">
                                    <text class="min">￥</text>
                                    <text class="max">{{item.vip_price}}</text>
                                </view>
                                <view class="num">
                                    <view class="add" @click="decreaseQuantity(index)">
                                        <text class="iconfont icon-jian"></text>
                                    </view>
                                    <view class="number">
                                        <text>{{item.quantity}}</text>
                                    </view>
                                    <view class="add" @click="increaseQuantity(index)">
                                        <text class="iconfont icon-jia"></text>
                                    </view>
                                </view>
                            </view>
                        </view>
                    </view>
                </view>
            </view>
            <!-- 为你推荐 -->
            <view class="recommend-info">
                <view class="recommend-title">
                    <view class="title">
                        <image src="/static/wntj_title.png" mode=""></image>
                    </view>
                </view>
                <view class="goods-list">
                    <view class="list" v-for="(item, index) in goodsList" @click="onSkip('goods')" :key="index">
                        <view class="pictrue">
                            <image :src="item.img" mode="heightFix"></image>
                        </view>
                        <view class="title-tag">
                            <view class="tag">
                                <text v-if="item.is_goods === 1">特价</text>
                                {{item.name}}
                            </view>
                        </view>
                        <view class="price-info">
                            <view class="user-price">
                                <text class="min">￥</text>
                                <text class="max">{{item.price}}</text>
                            </view>
                            <view class="vip-price">
                                <image src="/static/vip_ico.png"></image>
                                <text>￥{{item.vip_price}}</text>
                            </view>
                        </view>
                    </view>
                </view>
            </view>
            <!-- 结算 -->
            <view class="close-account">
                <view class="check-total">
                    <view class="check" @click="toggleAllSelection">
                        <text class="iconfont" :class="{ 'icon-checked': isAllSelected, 'icon-uncheck':!isAllSelected }"></text>
                        <text class="all">全选</text>
                    </view>
                    <view class="total">
                        <text>合计：</text>
                        <text class="price">￥{{calculateTotalPrice().toFixed(2)}}</text>
                    </view>
                </view>
                <view class="account">
                    <view class="btn-calculate" v-if="!isEdit">
                        <text>去结算({{getSelectedCount()}})</text>
                    </view>
                    <view class="btn-del" v-else>
                        <text class="attention" @click="moveToFavorite">移入关注</text>
                        <text class="del" @click="deleteSelectedItems">删除</text>
                    </view>
                </view>
            </view>
        </mescroll-body>
        <!-- tabbar -->
        <TabBar :tabBarShow="3"></TabBar>
    </view>
</template>

<script>
import cart from '../api/cart';
import TabBar from '../../components/TabBar/TabBar.vue';
import MescrollMixin from "@/components/mescroll-uni/mescroll-mixins.js";

export default {
    mixins: [MescrollMixin],
    components: {
        TabBar
    },
    data() {
        return {
            list: [],
            mescroll: null,
            downOption: {},
            upOption: {
                use: false,
                toTop: {
                    src: ''
                }
            },
            isEdit: false,
            goodsList: [
                // 原有的 goodsList 数据
            ]
        };
    },
    computed: {
        // 计算是否全选
        isAllSelected() {
            return this.list.every(item => item.selected);
        }
    },
    onReady() {
        uni.hideTabBar();
    },
    onLoad() {
        this.getCartList();
    },
    methods: {
        getCartList() {
            cart.cartList({
                user_id: 1
            }).then(res => {
                console.log(res);
                if (!res.data) {
                    console.log('商品未查到');
                    return;
                }
                // 为每个商品添加 selected 属性并初始化为 false
                this.list = res.data.map(item => ({ ...item, selected: false ,id:item.goods_id}));
            });
        },
        downCallback() {
            this.mescroll.endSuccess();
        },
        upCallback(page) {
            setTimeout(() => {
                this.mescroll.endByPage(10, 20);
            }, 2000);
        },
        onSkip(type) {
            switch (type) {
                case 'classify':
                    uni.navigateTo({
                        url: '/pages/SearchGoodsList/SearchGoodsList'
                    });
                    break;
                case 'goods':
                    uni.navigateTo({
                        url: '/pages/GoodsDetails/GoodsDetails',
                        animationType: 'zoom-fade-out',
                        animationDuration: 200
                    });
                    break;
            }
        },
        // 切换单个商品的选中状态
        toggleItemSelection(index) {
            this.list[index].selected = !this.list[index].selected;
        },
        // 切换全选状态
        toggleAllSelection() {
            const allSelected = this.isAllSelected;
            this.list.forEach(item => {
                item.selected = !allSelected;
            });
        },
        // 减少商品数量
        decreaseQuantity(index) {
            if (this.list[index].quantity > 1) {
                this.list[index].quantity--;
                cart.updateCart({
                    user_id: 1,
                    quantity: this.list[index].quantity,
                    goods_id: this.list[index].goods_id,
                    sku_id: this.list[index].sku_id,
                })
               .then(res => {
                    console.log('商品数量更新成功', res);
                })
               .catch(error => {
                    console.error('商品数量更新失败', error);
                });
            }
        },
        // 增加商品数量
        increaseQuantity(index) {
            this.list[index].quantity++;
            cart.updateCart({
                user_id: 1,
                quantity: this.list[index].quantity,
                goods_id: this.list[index].goods_id,
                sku_id: this.list[index].sku_id
            })
               .then(res => {
                    console.log('商品数量更新成功', res);
                })
               .catch(error => {
                    console.error('商品数量更新失败', error);
                });
        },
        // 计算选中商品的总价
        calculateTotalPrice() {
            return this.list.reduce((total, item) => {
                if (item.selected) {
                    return total + parseFloat(item.vip_price) * item.quantity;
                }
                return total;
            }, 0);
        },
        // 获取选中商品的数量
        getSelectedCount() {
            return this.list.filter(item => item.selected).length;
        },
        // 删除选中商品
        async deleteSelectedItems() {
            const selectedIds = this.list.filter(item => item.selected).map(item => item.id);
            console.log('筛选出的选中商品 ID 数组:', selectedIds); // 打印筛选出的商品 ID 数组
            if (selectedIds.length === 0) {
                uni.showToast({
                    title: '请选择要删除的商品',
                    icon: 'none'
                });
                return;
            }
        
            const sliceSize = 10; // 切片大小，可根据实际情况调整
            const slices = [];
            for (let i = 0; i < selectedIds.length; i += sliceSize) {
                slices.push(selectedIds.slice(i, i + sliceSize));
            }
        
            console.log('切片后的商品 ID 数组:', slices); // 打印切片后的商品 ID 数组
        
            try {
                for (const slice of slices) {
                    await cart.deleteCart({
                        user_id: 1,
                        goods_id: slice 
                    });
                }
                console.log('商品删除成功');
                // 更新本地购物车列表
                this.list = this.list.filter(item => !item.selected);
            } catch (error) {
                console.error('商品删除失败', error);
                uni.showToast({
                    title: '删除失败，请稍后重试',
                    icon: 'none'
                });
            }
        },
        // 移入关注（可根据实际需求实现）
        moveToFavorite() {
            const selectedItems = this.list.filter(item => item.selected);
            if (selectedItems.length === 0) {
                uni.showToast({
                    title: '请选择要移入关注的商品',
                    icon: 'none'
                });
                return;
            }
            // 调用移入关注的接口
            console.log('移入关注的商品：', selectedItems);
            // 可在这里添加实际的接口调用逻辑
        }
    }
};
</script>

<style scoped lang="scss">
    @import 'cart.scss';
</style>